<?php

namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class DBSqlListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle(QueryExecuted $event)
    {
        // 如果不是测试环境 ，不记录
        if(!app()->environment(['testing','local'])) {
            return ;
        }

        // 监听数据库事件,进行断点打印,并记录到sql日志中

        $sql = $event->sql;//执行的sql
        $bindings = $event->bindings;//执行的参数
        $time = $event->time;//执行的时间

        // 如果是字符串 带上引号
        $bindings = array_map(function ($binding) {
            if(is_string($binding)){
                return "'$binding'";
            } else if($binding instanceof \DateTime) { // 如果是时间
                return $binding->format("'Y-m-d H:i:s'");
            }
            return $binding;
        },$bindings);
        //拼装sql
        $sql = str_replace('?','%s',$sql);
        // 填充参数
        //$sql = vsprintf($sql,$bindings);
        $sql = sprintf($sql,...$bindings);
        // 记录到日志
        Log::info('sql log',['sql'=>$sql,'time' =>$time.'ms']);
        // 如果是测试环境 输出
        if(app()->environment(['testing'])) {
            echo $sql.PHP_EOL;
        }
    }
}
